
function addToCategories() {
    var new_category_input = $('#options input[name="new_category"]');
    var new_category = new_category_input.val();
    if (new_category !== '') {
        var found = false;
        var insert_before;
        $('#options select[name="job_category"] option').each(function() {
            if ($(this).text() === new_category) {
                found = true;
            }
            if ($(this).text() >= new_category) {
                insert_before = $(this);
                return false;
            }
        });
        if (!found) {
            var option = $('<option/>').text(new_category);
            if (insert_before === undefined) {
                $('#options select[name="job_category"]').append(option);
            } else {
                insert_before.before(option);
            }
        }
        new_category_input.val('');
    }
}

$('#add_category').click(addToCategories);
// need to figure this out gets overwritten by openDialog()
$('#new_category').keyup(function() {
    keycode = event.keyCode || event.which;
    if (keycode == RETURN) {
        addToJobs();
    }
});

$('#remove_category').click(function() {
    var selected = $('#options select[name="job_category"] option:selected');
    if (selected.length === 0) return;
    selected.each(function() {
        // only delete those which were previously saved
        if (this.value !== "") {
            $('<input type="hidden" class="delete" />').val(this.value).insertAfter('#options select[name="job_category"]');
        }
    });
    selected.remove();
});

$('select[name="job_category"]').editableOptions(function(option) {
    option.attr("dirty", "1");
});

